<template>
	
  <!-- 导航 -->
  <!-- <scroll-view class="sub-nav">
    <text class="sub-item" @click="goToPage('/pages/message/message-1/message-1')">被赞</text>
    <text class="sub-item">收藏</text>
    <text class="sub-item">新增关注</text>
  </scroll-view> -->

  <!-- 消息列表 -->
  <scroll-view class="message-list" scroll-y>
    <view 
      class="message-item" 
      :class="{unread: item.unread}"
      v-for="(item, index) in users" 
      :key="index"
	  @click="goToPage('/pages/message/chat/chat?userId='+item.id+'&userName='+item.username+'&avatarUrl='+item.avatar)"
    >
      <image class="avatar" :src="item.avatar"></image>
      <view class="content">
        <view class="header">
          <text class="username">{{item.username}}</text>
          <text class="time">{{formatTimestamp(item.time) }}</text>
        </view>
        <text class="preview">{{item.preview}}</text>
        <text class="badge" v-if="item.badge!=0">{{item.badge}}</text>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { http } from '../../../utils/request'
import { formatTimestamp } from '../../../utils/dateUtils'
const socketState = reactive({
  socketTask: null,
  messages: []
})
const users = ref([])
onShow(async()=>{
	console.log("onshow");
	try{
		const currentUserId = uni.getStorageSync('userId')
		const res = await http.get('/api/messages/recent',{
			currentUserId 
		})
		users.value = res.map(item=>{
			console.log(item);
			return{
				id: item.userId,
				avatar: item.avatar,
				username: item.userNickname,
				time: item.lastMessage.timestamp,
				preview: item.lastMessage.content,
				unread: !item.lastMessage.isRead,
				badge: item.unreadCount
			}
		})
		// console.log("arr:",arr);
		
	}catch(e){
		console.log("获取用户列表失败：",e);
	}
})
onMounted(async () => {
  const header = {
    'Authorization': `Bearer ` + uni.getStorageSync('token')
  }
  
  try {
    socketState.socketTask = await uni.connectSocket({
      url: 'ws://192.168.31.45:8080/chat',
      header,
      success: () => {
        console.log('WebSocket 连接创建成功')
      },
      fail: (err) => {
        console.error('WebSocket 连接失败:', err)
      }
    })

    // 监听WebSocket消息
    socketState.socketTask.onMessage((res) => {
      console.log('收到消息:', JSON.parse(res.data))
      const message = JSON.parse(res.data)
      socketState.messages.unshift({
        ...message,
        time: new Date().toLocaleTimeString(),
        unread: true,
        badge: 1
      })
      if(message.type === 'LOGIN') return
      
      // 获取当前页面路由
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1].route
      
      if (currentPage === 'pages/message/chat/chat') {
        uni.$emit('newMessage', message);
      } else if (currentPage === 'pages/tabbar/tabbar-4/tabbar-4') {
        const index = users.value.findIndex(item=>item.id===message.fromUserId)
        console.log(users.value[index])
        console.log('1',users.value[index].badge)
        users.value[index].badge++
        users.value[index].preview = message.content
        users.value[index].time = message.timestamp
        
        uni.showToast({
          title: JSON.parse(res.data).content
        })
      }
    })

    // 监听WebSocket关闭
    socketState.socketTask.onClose(() => {
      console.log('WebSocket 连接已关闭')
    })

    // 监听WebSocket错误
    socketState.socketTask.onError((err) => {
      console.error('WebSocket 错误:', err)
    })

  } catch (err) {
    console.error('WebSocket 初始化错误:', err)
  }
})

onUnmounted(() => {
  if (socketState.socketTask) {
    socketState.socketTask.close()
  }
})
const messages = ref([])
	
// 合并静态消息和WebSocket消息并按时间排序
const allMessages = [...messages.value, ...socketState.messages].sort((a, b) => {
  // 简单按时间字符串排序 - 实际项目中应该使用Date对象比较
  return b.time.localeCompare(a.time)
})

const goToPage = (url) => {
  if (!url) return
  uni.navigateTo({
    url
  })
}
</script>

<style>
.sub-nav {
  padding: 12px;
  white-space: nowrap;
  border-bottom: 1px solid #f5f5f5;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}

.sub-item {
  display: inline-block;
  padding: 8px 16px;
  color: #666;
}


.message-list {
  height: calc(100vh - 140px);
  padding: 12px;
  width: 100%;
  box-sizing: border-box;
}

.message-item {
  display: flex;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #f8f8f8;
  width: 100%;
  box-sizing: border-box;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 24px;
  margin-right: 12px;
}

.content {
  flex: 1;
  position: relative;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.preview {
  color: #666;
  font-size: 14px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.unread .preview {
  font-weight: 500;
  color: #333;
}

.badge {
  position: absolute;
  right: 0;
  top: 70%;
  transform: translateY(-50%);
  background-color: #ff4d4f;
  color: white;
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  padding: 0 4px;
}

</style>
